//
//  SHUserSetttingController.m
//  JiFengDaRen
//
//  Created by SH_iOS on 2017/5/27.
//  Copyright © 2017年 SH_iOS. All rights reserved.
//
#import "SHUserCenterHttp.h"
#import "UserModel.h"
#import "XDActionSheet.h"//弹出视图
#import "SHUserHeaderImgSettingCell.h"//头像cell
#import "SHUserSettingCell.h"//用户设置基本cell
#import "SHUserLogoutCell.h"//退出登录cell
#import "JFLoginViewController.h"//登录页面
#import "SHModifyUserInfoViewController.h"//修改昵称 邮箱
#import "SHUserPayPasswordController.h"//设置支付密码
#import "SHUserResetPasswordController.h"//重置支付密码
#import "SHAboutAppViewController.h"//应用基本信息
#import "ForgetPswViewController.h"//修改密码
#import "SHUserSetttingController.h"

@interface SHUserSetttingController ()<UITableViewDataSource,UITableViewDelegate,XDActionSheetDatasource,XDActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,SHModifyUserInfoViewControllerDelegate>
@property(nonatomic,strong)UITableView *userSettingTableView;
@property(nonatomic,strong)NSArray  *dataListArray;
@property(nonatomic,strong)XDActionSheet *sheet;
@property(nonatomic,strong)NSArray *titleArrary;
@end

@implementation SHUserSetttingController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configUI];

    
    // Do any additional setup after loading the view.
}


#pragma mark - 初始化UI
- (void)configUI{
    self.navigationItem.title = @"个人设置";
    [self userSettingTableView];
    _userSettingTableView.estimatedSectionHeaderHeight = 0;
    _userSettingTableView.estimatedSectionFooterHeight = 0;
}

#pragma mark - 懒加载
- (NSArray *)dataListArray{
    if (!_dataListArray) {
        _dataListArray = @[
                           @[@{@"title":@"昵称"},@{@"title":@"修改邮箱"}],
                           @[@{@"title":@"设置支付密码"},@{@"title":@"修改密码"}],
                           @[@{@"title":@"关于"}],
                        ];
        ;
    }
    
    return _dataListArray;
}

static NSString *const userSettingCellHeaderImgID =  @"userSettingCellHeaderImgID";
static NSString *const userSettingCellCenterID =  @"userSettingCellCenterID";
static NSString *const userSettingCellLogoutID =  @"userSettingCellLogoutID";
#pragma mark - 列表
- (UITableView *)userSettingTableView{
    
    if (!_userSettingTableView) {
        _userSettingTableView  = [[UITableView alloc]initWithFrame:CGRectMake(0,0, KScreenWidth, KScreenHeight - KNAVIGATIONBARHEIGHT) style:UITableViewStyleGrouped];
        _userSettingTableView.dataSource = self;
        _userSettingTableView.delegate = self;
        _userSettingTableView.showsVerticalScrollIndicator = NO;
        _userSettingTableView.backgroundColor  = KBASEBGCOLOR;
        _userSettingTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_userSettingTableView registerClass:[SHUserHeaderImgSettingCell class] forCellReuseIdentifier:userSettingCellHeaderImgID];
        [_userSettingTableView registerClass:[SHUserSettingCell class] forCellReuseIdentifier:userSettingCellCenterID];
        [_userSettingTableView registerClass:[SHUserLogoutCell class] forCellReuseIdentifier:userSettingCellLogoutID];

        [self.view addSubview:_userSettingTableView];
    }
    return  _userSettingTableView;
}




#pragma mark - 列表delegate & dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0 || section == 3 || section == 4) {
        return 1;
    }
    
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
       return  __I6Height(76);
    }
    return __I6Height(45);
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0.01;
    }
    return __I6Height(12);

}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, __I6Height(12))];
    view.backgroundColor = KBASEBGCOLOR;
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SHUserHeaderImgSettingCell *headerImgCell;
    SHUserSettingCell     *centerCell;
    SHUserLogoutCell *logoutCell;
    
    if (indexPath.section == 0) {
        headerImgCell = [tableView dequeueReusableCellWithIdentifier:userSettingCellHeaderImgID];
        [headerImgCell setHeaderImgUrl:[UserModel shareManager].avatar];
        return headerImgCell;
    }else if (indexPath.section == 1 || indexPath.section == 2 || indexPath.section == 3 ){
        centerCell = [tableView dequeueReusableCellWithIdentifier:userSettingCellCenterID];
  
        [self setDataForCell:centerCell indexPath:indexPath];
        
        return centerCell;
        
    }else{
        
        logoutCell = [tableView dequeueReusableCellWithIdentifier:userSettingCellLogoutID];

        
        
        
        return logoutCell;
    }
    
    
    
}


- (void)setDataForCell:(SHUserSettingCell *)cell indexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 1) {
        
        if (indexPath.row == 0) {
            cell.contentLabel.text = [UserModel shareManager].nickname;
            cell.line.backgroundColor = KLINECOLOR;

        }else{
            cell.contentLabel.text = [UserModel shareManager].email;
            cell.line.backgroundColor = [UIColor clearColor];
        }
         NSString *title  = self.dataListArray[0][indexPath.row][@"title"];
        [cell setTitle:title];
    }else if (indexPath.section == 2){
        
       

        NSString *title = self.dataListArray[1][indexPath.row][@"title"];
        [cell setTitle:title];
        
        if (indexPath.row == 1) {
            cell.line.backgroundColor = [UIColor clearColor];
            
        }else{
            cell.line.backgroundColor = KLINECOLOR;
            if ([UserModel shareManager].has_pay_password ) {
                [cell setTitle:@"重置支付密码"];
            }
        }
    }else if(indexPath.section == 3){
        NSString *title = self.dataListArray[2][indexPath.row][@"title"];
        [cell setTitle:title];

        if (indexPath.row == 0) {
            cell.line.backgroundColor = [UIColor clearColor];
            
        }else{
            cell.line.backgroundColor = KLINECOLOR;
        }


    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [tableView deselectRowAtIndexPath:indexPath animated:NO];

        
    });
   

    if (indexPath.section == 0) {//修改头像
        self.titleArrary = @[@"相册",@"拍照",@"取消"];
        [self sheet];
        [_sheet actionSheetShow:self.titleArrary.count];
    }else if(indexPath.section == 1){//设置昵称 邮箱
        SHModifyUserInfoViewController *modifyUserInfoVc = [[SHModifyUserInfoViewController  alloc]init];
        modifyUserInfoVc.userInfoDelegate = self;
        if (indexPath.row == 0) {
            modifyUserInfoVc.key = @"nickname";

        }else{
            modifyUserInfoVc.key = @"email";

        }
        [self.navigationController pushViewController:modifyUserInfoVc animated:YES];
        
    }else if(indexPath.section == 2){//设置支付密码  登录密码
        if(indexPath.row == 0 ){//重置支付密码
            if ([UserModel shareManager].has_pay_password ) {
               
                SHUserResetPasswordController *payPassWordVc = [[SHUserResetPasswordController alloc]init];
                [self.navigationController pushViewController:payPassWordVc animated:YES];
                
            }else{//设置支付密码
                
                SHUserPayPasswordController *payPassWordVc = [[SHUserPayPasswordController alloc]init];
                [self.navigationController pushViewController:payPassWordVc animated:YES];
            }
            
        }else{
            [self.navigationController pushViewController:[[ForgetPswViewController alloc]init] animated:YES];

            
        }
        
    }else if(indexPath.section == 3){//设置推送 关于
        
        if (indexPath.row == 0) {//融云设置声音 推送
           
//            [self.view makeToast:@"开发中" duration:2.f position:@"center"];
            SHAboutAppViewController *aboutAppVc = [[SHAboutAppViewController alloc]init];
            [self.navigationController pushViewController:aboutAppVc animated:YES];
            
        }else{//应用简介
            
        }
    }else{//退出登录
        [self userLogOut];
    }
    
    
}

#pragma mark - 拍照弹出视图
static NSString *xdActionSheetreuserId = @"xdActionSheetreuserId";
- (XDActionSheet *)sheet{
    _sheet = [[XDActionSheet alloc]initWithFrame:CGRectZero];
    _sheet.delegate = self;
    _sheet.datasource = self;
    [_sheet registerClass:[UITableViewCell class] forCellReuseIdentifier:xdActionSheetreuserId];
    [[UIApplication sharedApplication].keyWindow addSubview:_sheet];
    return _sheet;
}

- (NSInteger)popoverListView:(XDActionSheet *)sheet numberOfRowsInSection:(NSInteger)section{
    
    
    return  self.titleArrary.count - 1;
    
}

- (UITableViewCell *)popoverListView:(XDActionSheet *)sheet cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        UITableViewCell *cell = [sheet dequeueReusablePopoverCellWithIdentifier:xdActionSheetreuserId];
        
        cell.textLabel.text = self.titleArrary[indexPath.row];
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        cell.textLabel.font = KSHSystemFont(15);
        if (indexPath.row < self.titleArrary.count - 2) {
            UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, __I6Height(45)-0.5, [UIScreen mainScreen].bounds.size.width,0.5)];
            line.backgroundColor = KLINECOLOR;
            
            
            [cell addSubview:line];
        }
        
        return cell;
        
    }else{
        UITableViewCell *cell = [sheet dequeueReusablePopoverCellWithIdentifier:xdActionSheetreuserId];
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        cell.textLabel.font = KSHSystemFont(15);
        
        cell.textLabel.text = [self.titleArrary lastObject];
        return cell;
        
    }
    
    
}

//======  开始拍照======
- (void)popoverListView:(XDActionSheet *)sheet didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {//相册
            [self LocalPhoto];
            
        }else{//拍照

            [SHHelper checkUserAVAuthorizationStatusVc:self complection:^(AVAuthorizationStatus status) {
                [self takePhoto];

            }];

            
        }
    }
    
}




//从相册选择
-(void)LocalPhoto{
    //打开系统相册
    [self openImagePickerController:UIImagePickerControllerSourceTypePhotoLibrary];}

//拍照
-(void)takePhoto{
    
    //****先检测相机权限
    

    //判断相机是否可用
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        //打开相机
        [self openImagePickerController:UIImagePickerControllerSourceTypeCamera];
     
        
        
        
    }else{
        
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"相机不可用" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        
        [alert show];
    }
}
#pragma mark - 打开相机
- (void)openImagePickerController:(UIImagePickerControllerSourceType)type{
    
    UIImagePickerController  *picker = [[UIImagePickerController alloc]init];
    //指定资源类型
    picker.sourceType = type;
    //允许编辑
    picker.allowsEditing = YES;
    picker.delegate = self;
    //弹出
    [self presentViewController:picker animated:YES completion:nil];
    SHLog(@"开始拍照");
    
    
}
#pragma mark - 系统相机代理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    @weakify(self)
    [picker dismissViewControllerAnimated:YES completion:^{
    @strongify(self)
        UIImage * image  = info[UIImagePickerControllerEditedImage];
        [self uploadUserHeaderImage:image];
    }];
    
}



#pragma mark - 上传图片
- (void)uploadUserHeaderImage:(UIImage *)image{

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [hud hideAnimated:YES afterDelay:1.f];
    [SHQiniuManager qiniuUploadImage:image scale:YES size:CGSizeMake(300, 300) complete:^(NSString *qnImageUrl){
        
        NSDictionary *params = @{@"headimgurl":qnImageUrl};
        [MyDataService requestAFURL:KChangeUser_info httpMethod:@"PUT" params:params data:nil complection:^(id result) {
            [UserModel shareManager].avatar = qnImageUrl;
            //回到主线程 更新头像
            dispatch_async(dispatch_get_main_queue(),^{
                [self.userSettingTableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
            });
            
            
        } failure:^(id erro) {
            
        }];
    }];
   
    
    
    
    
}


#pragma mark - 用户退出登录
- (void)userLogOut{
    
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [MyDataService requestAFURL:Kalogout httpMethod:@"POST" params:nil data:nil complection:^(id result) {
        [MBProgressHUD hideHUDForView:self.view animated:YES ];
        if ([result[@"success"] isEqualToNumber:@(1)]) {
            [Tool setObject:nil forKey:@"isSdUser"];
            [Tool setObject:nil forKey:KLoginStatusCookie];
            //清除 实名，银行卡信息完善状态
            [Tool setBool:NO forKey:KUserAuthBankStatus];
      
            [self.navigationController pushViewController:[[JFLoginViewController alloc]init] animated:YES];
        }
    } failure:^(id erro) {
        [MBProgressHUD hideHUDForView:self.view animated:YES ];

    }];
    

}


#pragma mark - 刷新昵称或者邮箱
- (void)startRefreshUserInfo{
    
    [self.userSettingTableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
